//
//  TabMineDetailTableViewController.swift
//  kz
//
//  Created by Tech_001 on 14/8/2017.
//  Copyright © 2017 Tech_001. All rights reserved.
//

import Foundation
import UIKit
import SwiftyJSON
class TabMineDetailTableViewController: UITableViewController{
    @IBOutlet weak var loginNameLabel: UILabel!
    @IBOutlet weak var realNameLabel: UILabel!
    @IBOutlet weak var birthLabel: UILabel!
    
    @IBOutlet weak var realNameCell: UITableViewCell!
    @IBOutlet weak var emailLabel: UILabel!
    @IBOutlet weak var mobileLabel: UILabel!
    @IBOutlet weak var qqLabel: UILabel!
    @IBOutlet weak var regTimeLabel: UILabel!
    @IBOutlet weak var versionLabel: UILabel!
    @IBOutlet weak var cacheLabel:UILabel!
    
    @IBOutlet weak var dodCell: UITableViewCell!
    @IBOutlet weak var telCell: UITableViewCell!
    @IBOutlet weak var emailCell: UITableViewCell!
    @IBOutlet weak var getMoneyLab: UILabel!
    @IBOutlet weak var getMoneyCell: UITableViewCell!
    @IBOutlet weak var xianlulab: UILabel!
    var jsonData : JSON?
    var baseInfo: UserInfoModel?
    override func viewDidAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationItem.backBarButtonItem?.title = ""
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.navigationItem.title = "个人中心"
        self.view.backgroundColor = UIColor.init("F8F9FB")
        // 设置导航栏默认返回按钮
        self.leftButtonActionWithImg("icon_default_back")
        
        self.tableView.estimatedRowHeight = 44;
        self.tableView.rowHeight = UITableView.automaticDimension;
        self.xianlulab.text =  GlobalInfo.CircuitContent
        
        initUI()
        
        NotificationCenter.default.addObserver(self, selector: #selector(goTobankList), name: NSNotification.Name(rawValue: "checkBankSucess"), object: nil)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        // 还原导航栏下面的一条线
        self.navigationController?.navigationBar.shadowImage = nil
           showInfo()
       }
    
    func initUI() {
        
        self.baseInfo = GlobalInfo.baseInfoData
        
        loginNameLabel.text = baseInfo?.username
        realNameLabel.text = baseInfo?.realname
        birthLabel.text = baseInfo?.dob
        
        emailLabel.text = baseInfo?.email
        
        if baseInfo != nil {
            let sring1  = baseInfo!.profile_address
            let string2 = baseInfo!.profile_street
            qqLabel.text = sring1 + string2
        }
        if qqLabel.text == "" {
            qqLabel.text = "  "
        }
        let version:String = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String
        var string = version + getVersionString()
        //如果配置文件isTest 为true。 并且gamejson地址是game.manbetlegend.com
        if(isTest && GlobalInfo.resDomain.contains("manbetlegend")){
            string.append("-test")
        }
        versionLabel.text = string
        cacheLabel.text = "\(fileSizeOfCache())M"
        if self.jsonData != nil {
            if jsonData!["realname"]["edittable"] != "yes"{
                self.realNameCell.accessoryType = .none
            }else{
                self.realNameCell.accessoryType = .disclosureIndicator
            }
            if(jsonData!["dob"]["edittable"] != "yes"){
                dodCell.accessoryType = .none
            }else{
                dodCell.accessoryType = .disclosureIndicator
            }
            if(jsonData!["email"]["can_verify"] != "yes"){
                emailCell.accessoryType = .none
            }else{
                emailCell.accessoryType = .disclosureIndicator
            }
            if(jsonData!["mobile"]["can_verify"] != "yes"){
                if(jsonData!["mobile"]["can_cancel"] == 0){
                    telCell.accessoryType = .none
                    if let content = baseInfo?.mobile{
                        let attributStr = NSMutableAttributedString.init(string: "\(content)  ")
                        let cancelStyle : [ NSAttributedString.Key:Any] = [
                            NSAttributedString.Key.font:UIFont.systemFont(ofSize: 13),
                            NSAttributedString.Key.underlineStyle:NSUnderlineStyle.single.rawValue
                        ]
                        let cancel = NSAttributedString.init(string: "取消验证", attributes: cancelStyle)
                        attributStr.append(cancel)
                        mobileLabel.attributedText = attributStr
                    }
                }else{
                    telCell.accessoryType = .disclosureIndicator
                    if let content = baseInfo?.mobile{
                        let attributeString = NSMutableAttributedString.init(string: content)
                        mobileLabel.attributedText = attributeString
                    }
                }
            }else{
                telCell.accessoryType = .disclosureIndicator
                if let content = baseInfo?.mobile{
                    let attributeString = NSMutableAttributedString.init(string: content)
                    mobileLabel.attributedText = attributeString
                }
            }
            
            if jsonData!["wdPassword"].stringValue == "no_need"{
               
            }else if jsonData!["wdPassword"].stringValue == "can_edit"{
                getMoneyCell.height = 44.0
                getMoneyLab.text = "修改取款密码"
            }else{
                getMoneyCell.height = 44.0
                getMoneyLab.text = "修改取款密码"
            }
            tableView.reloadData()
        }
    }
    
    // 导航栏左边按钮
    func leftButtonActionWithImg(_ image: String) {
        let naviLeftButton = UIButton.init(type: UIButton.ButtonType.custom)
        naviLeftButton.frame = CGRect.init(x: 0, y: 0, width: 22, height: 22);
        naviLeftButton.setBackgroundImage(UIImage.init(named: image), for: UIControl.State.normal)
        naviLeftButton.setBackgroundImage(UIImage.init(named: image), for: UIControl.State.highlighted)
        naviLeftButton.addTarget(self, action: #selector(doLeftNaviAction), for: UIControl.Event.touchUpInside)
        self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(customView: naviLeftButton)
    }
    
    // 导航栏左边按钮点击
    @objc func doLeftNaviAction() {
        self.navigationController?.popViewController(animated: true)
    }
    
    func showInfo(){
        weak var this = self
        RequestHelper.post(atPath: "/clientsAPIs/GetProfileInfo",  withData:Dictionary(), withCompletion: { data in
            let json = JSON(data)
//            print("~~~\(json)")
            this?.jsonData = json[0]
            GlobalInfo.baseInfoData = UserInfoModel.changeJsonTomModel(json: json[0])
            
             DispatchQueue.main.async {
                this?.initUI()
//                this?.tableView.reloadData()
            }
        }, withError: { error in
             UIHelper.alertSimpleMessage(about: "服务器异常,\(getErrorString())", withDescription: "", in: self)
        })
    }
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return 3
        }else if section == 1{
            return 3
        }else if section == 2{
            if self.jsonData != nil {
                if jsonData!["wdPassword"].stringValue == "no_need"{
                    return 2
                
                }else{
                    return 3
                }
            }else{
                return 3
            }
        }else{
            return 4
        }
    }
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        if indexPath.section == 0 {
            if UserHelper.getLoginStatus() == false {
                LoginViewController.loginIfNeedController(currentController: self) {}
                return
            }
            if indexPath.row == 1{
                ToolHelper.statisticsPage(pageName: "我的-个人中心-真实姓名")
                if((self.jsonData) != nil){
                    if(self.jsonData!["realname"]["edittable"] != "yes"){
                        UIHelper.alertSimpleMessage(about: "不可重复修改", withDescription: "请联系客服", in: self)
                        return
                    }
                    let vc = UpdateUserInfoViewController()
                    self.navigationController?.pushViewController(vc, animated: true)
                }
            }else  if indexPath.row == 2{
               ToolHelper.statisticsPage(pageName: "我的-个人中心-出生日期")
                if((self.jsonData) != nil){
                    if(self.jsonData!["dob"]["edittable"] != "yes"){
                    UIHelper.alertSimpleMessage(about: "不可重复修改", withDescription: "请联系客服", in: self)
                    return
                    }
                    let vc = UpdateUserBirthDateController()
                    self.navigationController?.pushViewController(vc, animated: true)
                }
            }
        }else if indexPath.section == 1 {
            if UserHelper.getLoginStatus() == false {
                LoginViewController.loginIfNeedController(currentController: self) {}
                return
            }
            if indexPath.row == 0{
                ToolHelper.statisticsPage(pageName: "我的-个人中心-邮箱地址")
                 if((jsonData) != nil){
                    if(jsonData!["email"]["can_verify"] != "yes"){
                        UIHelper.alertSimpleMessage(about: "不可重复修改", withDescription: "请联系客服", in: self)
                        return
                    }
                let vc = UpdateUserEmailViewController()
                self.navigationController?.pushViewController(vc, animated: true)
                }
            }else if indexPath.row == 1 {
                ToolHelper.statisticsPage(pageName: "我的-个人中心-手机号码")
                if((jsonData) != nil){
                    if(jsonData!["mobile"]["can_verify"] == "yes"){
                        //可验证。跳转绑定
                        let vc = UpdateUserTelephone()
                        self.navigationController?.pushViewController(vc, animated: true)
                    }else{
                        //已经验证过，并且是可取消状态，取消验证
                        if(jsonData!["mobile"]["can_cancel"] == 0){
                            showDialog()
                        }else{
                            UIHelper.alertSimpleMessage(about: "不可重复修改", withDescription: "请联系客服", in: self)
                        }
                    }
                }
            }else if indexPath.row == 2 {
                ToolHelper.statisticsPage(pageName: "我的-个人中心-收货地址")
                let vc = UpdateAddressViewController()
                self.navigationController?.pushViewController(vc, animated: true)
            }
        }else if indexPath.section == 2 {
            if UserHelper.getLoginStatus() == false {
                LoginViewController.loginIfNeedController(currentController: self) {}
                return
            }
            if indexPath.row == 0 {
                ToolHelper.statisticsPage(pageName: "我的-个人中心-修改登录密码")
                let vc = UpdatePwdVC()
                vc.requestType = UpdatePwdType.login
                self.navigationController?.pushViewController(vc, animated: true)
            }else if indexPath.row == 1 {
                ToolHelper.statisticsPage(pageName: "我的-个人中心-取款银行卡")
                checkBaknThority()
            }else if indexPath.row == 2 {
                ToolHelper.statisticsPage(pageName: "我的-个人中心-取款密码")
                let vc = UpdateBankPwdViewController()
                vc.requestType = UpdatePwdType.withdraw
                self.navigationController?.pushViewController(vc, animated: true)
            }
        }else if indexPath.section == 3 {
            if indexPath.row == 2 {
                ToolHelper.statisticsPage(pageName: "我的-个人中心-检测版本")
                checkUpdate()
            }else if indexPath.row == 3 {
                ToolHelper.statisticsPage(pageName: "我的-个人中心-清除缓存")
                self.mtClaerCatcheSize()
            }
        }
    }
    func showDialog(){
        let mtDialogMessage = UIAlertController(title:"提示",message:"用户只有取消验证一次机会，是否继续？",preferredStyle: .alert)
              mtDialogMessage.view.tintColor = UIColor.black
              let ok = UIAlertAction(title:"是",style:.default,handler:{(action)->Void in
                    self.cancelMobile()
                }
              )
              mtDialogMessage.addAction(ok)
              let no = UIAlertAction(title:"否",style:.default,handler: { (action) -> Void in
                self.telCell.accessoryType = .disclosureIndicator
                if let content = self.baseInfo?.mobile{
                    let attributeString = NSMutableAttributedString.init(string: content)
                    self.mobileLabel.attributedText = attributeString
                }              })
              mtDialogMessage.addAction(no)
              DispatchQueue.main.async {
                  self.present(mtDialogMessage, animated: true, completion: nil)
              }
    }

    var _loadView:UIView?
    func checkBaknThority()  {
        weak var this  = self
        self._loadView = UIHelper.initLoadView(self, withMessage: "读取中...")
        self.view.addSubview(_loadView!)
        RequestHelper.post(atPath: "/clientsAPIs/GetVerificationState", withData:["pagetype":"ADD_BANKCARD_PAGE"], withCompletion: { data in
            
            let json = JSON(data)
            if json.stringValue == "SHOW_VERIFICATION_PAGE"{
                // 需验证
                this!.getCodeDetail()
             
            }else{
                // 不需验证
                DispatchQueue.main.async {
                    this?._loadView?.removeFromSuperview()
                    let vc = BankListController()
                    this!.navigationController?.pushViewController(vc, animated: true)
                }
            }
        },withError: {_ in
            UIHelper.alertSimpleMessage(about: "服务器异常,验证信息失败.\(getErrorString())", withDescription: "", in: self)
        })
    }
   @objc func goTobankList() {
        let vc = BankListController()
        self.navigationController?.pushViewController(vc, animated: true)
    }
    func getCodeDetail() {
        
        weak var this = self
        RequestHelper.post(atPath: "/clientsAPIs/GetVerificationAction", withData:["pagetype":"ADD_BANKCARD_PAGE"], withCompletion: { data in
            let json = JSON(data)
            DispatchQueue.main.async {
                let cont = BankListFillUpController()
                if  json["has_realname"].stringValue == "no"{
                    //需验证真实姓名
                    cont.needName = "true"
                }
                if json["has_mobile"].stringValue == "no"{
                    //需验证手机号
                    cont.needTel = "true"
                }
                this?._loadView?.removeFromSuperview()
                this!.navigationController?.pushViewController(cont, animated: true)
            }
            
        },withError: {_ in
             UIHelper.alertSimpleMessage(about: "服务器异常,获取验证信息失败.\(getErrorString())", withDescription: "", in: self)
        })
    }
    func mtClaerCatcheSize(){
        let mtDialogMessage = UIAlertController(title:"清除缓存",message:"是否清除缓存",preferredStyle: .alert)
        mtDialogMessage.view.tintColor = UIColor.black
        let ok = UIAlertAction(title:"是",style:.default,handler:{(action)->Void in
            self.mtClearCache()
            self.cacheLabel.text = "\(self.fileSizeOfCache())M"
            UIHelper.alertSimpleMessage(about: "缓存已被清除", withDescription: "", withOKButton: false)
             ToolHelper.statisticsPage(pageName: "个人中心-清除缓存-是")
        }
        )
        mtDialogMessage.addAction(ok)
        let no = UIAlertAction(title:"否",style:.default,handler: { (action) -> Void in
              ToolHelper.statisticsPage(pageName: "个人中心-清除缓存-否")
        })
        mtDialogMessage.addAction(no)
        DispatchQueue.main.async {
            self.present(mtDialogMessage, animated: true, completion: nil)
        }
    }
    
    //缓存大小
    func fileSizeOfCache()-> String {
        // 取出cache文件夹目录 缓存文件都在这个目录下
        let cachePath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first
        
        // 缓存目录路径
        // 取出文件夹下所有文件数组
        
        let fileArr = FileManager.default.subpaths(atPath: cachePath!)
        //快速枚举出所有文件名 计算文件大小
        var size:Float = 0
        for file in fileArr! {
            // 把文件名拼接到路径中
            let path = (cachePath! as NSString).appending("/\(file)")
            // 取出文件属性
            let floder = try! FileManager.default.attributesOfItem(atPath: path)
            // 用元组取出文件大小属性
            for (abc, bcd) in floder {
                // 累加文件大小
                if abc == FileAttributeKey.size {
                    size += (bcd as AnyObject).floatValue
                }
            }
        }
        let mm : Float = Float(size / 1024.0/1024.0)
        if (mm == 0){
            return "0"
        }
        return String(format: "%.2f", size / 1024.0 / 1024.0 ) as String
    }
    //清除缓存
    func mtClearCache() {
        // 取出cache文件夹目录 缓存文件都在这个目录下
        let cachePath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first
        
        // 取出文件夹下所有文件数组
        let fileArr = FileManager.default.subpaths(atPath: cachePath!)
        // 遍历删除
        for file in fileArr! {
            let path = (cachePath! as NSString).appending("/\(file)")
            if FileManager.default.fileExists(atPath: path) {
                do {
                    try FileManager.default.removeItem(atPath: path)
                } catch {
                }
            }
        }
    }
    
    func checkUpdate(){
        let nsObject = Bundle.main.infoDictionary?["CFBundleShortVersionString"]
        let version = nsObject as! NSString
        
        RequestHelper.get(GlobalInfo.resDomain, atPath: "/\(GlobalInfo.versionFileManually)", withCompletion: { (data: Data) -> Void in
            if let dataArray = try JSONSerialization.jsonObject(with: data, options: []) as? [String: String] {
                DispatchQueue.main.async {
                    print("版本号\(dataArray)")
                    let latestVersion = dataArray["version"]! as NSString
                    if latestVersion.floatValue > version.floatValue && dataArray["READY_TO_UPDATE"] == "true"{
                        let dialogMessage = UIAlertController(title: dataArray["TIP_TITLE"], message: dataArray["TIP_CONTENT"], preferredStyle: .alert)
                        dialogMessage.view.tintColor = UIColor.black
                        
                        let ok = UIAlertAction(title: "是", style: .default, handler: { (action) -> Void in
                             if dataArray["iosdownload"] != nil{
                                if let url = URL(string: dataArray["iosdownload"]!), UIApplication.shared.canOpenURL(url) {
                                    UIApplication.shared.openURL(url)
                                }
                             }
                       
                            if(dataArray["FORCE_TO_UPDATE"] == "true"){
                                self.present(dialogMessage, animated: true, completion: nil)
                            }
                        })
                        dialogMessage.addAction(ok)
                        
                        if(dataArray["FORCE_TO_UPDATE"] != "true"){
                            let no = UIAlertAction(title: "否", style: .default, handler: { (action) -> Void in
                            })
                            dialogMessage.addAction(no)
                        }
                        
                        // Present dialog message to user
                        DispatchQueue.main.async {
                            self.present(dialogMessage, animated: true, completion: nil)
                        }
                    }else if latestVersion.floatValue > version.floatValue && dataArray["FORCE_TO_UPDATE"] == "true"{
                        let dialogMessage = UIAlertController(title: dataArray["TIP_TITLE"], message: dataArray["TIP_CONTENT"], preferredStyle: .alert)
                        dialogMessage.view.tintColor = UIColor.black
                        
                        let ok = UIAlertAction(title: "是", style: .default, handler: { (action) -> Void in
                            if dataArray["iosdownload"] != nil{
                                if let url = URL(string: dataArray["download"]!), UIApplication.shared.canOpenURL(url) {
                                    //    self.shouldCheckUpdate = false
                                    UIApplication.shared.openURL(url)
                                }
                            }
                            self.present(dialogMessage, animated: true, completion: nil)
                            
                        })
                        dialogMessage.addAction(ok)
                        DispatchQueue.main.async {
                            self.present(dialogMessage, animated: true, completion: nil)
                        }
                    }else{
                        DispatchQueue.main.async {
                            PopWindowHelper.showNewVersionPopView(title: "版本\(version)" as NSString, subTitle: "当前已经是最新版本!")
                        }
                    }
                }
            }else{
                DispatchQueue.main.async {
                    PopWindowHelper.showNewVersionPopView(title: "版本\(version)" as NSString, subTitle: "当前已经是最新版本!")
                }
            }
        }, withError: { error in
            print(error)
            DispatchQueue.main.async {
                PopWindowHelper.showNewVersionPopView(title: "版本\(version)" as NSString, subTitle: "当前已经是最新版本!")
            }
        })
    }
    
    func navigateWebView(toPath: String, _ title: String){
        let goNext: WebViewController = WebViewController.init()
        let url = "https://" + UserDefaults.standard.string(forKey: DefaultKey.USER_DOMAIN)! + toPath
        goNext.url = url
        goNext.title = title
        goNext.bottomOffset = 0
        
        goNext.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(goNext, animated: true)
    }
    
    func cancelMobile(){
               let progress = MBProgressHUD.showMessageNoHiden("", to: self.view)
               NetWorkRequest(API.cancelMobile(url: "b96c34e", ccToken: API.getCcToken(), vcToken: API.getVcToken()), completion: { (responseData,statusCode,strData) -> (Void) in
                   DispatchQueue.main.async {
                       progress.removeFromSuperview()
                       let vc = UpdateUserTelephone()
                       self.navigationController?.pushViewController(vc, animated: true)
//                       self.showInfo()
                   }},failed: {(faildInfo,reCode,msg) -> (Void) in
                       DispatchQueue.main.async {
                        progress.removeFromSuperview()
                       UIHelper.alertSimpleMessage(about: "\(faildInfo)", withDescription: "", in: self)
                        
                         //  self.tableView.mj_header?.endRefreshing()
                       }
               }){() -> (Void) in
                   DispatchQueue.main.async {
                      // self.dismissLoadHUD()
                       progress.removeFromSuperview()
                       UIHelper.alertSimpleMessage(about: "网络请求异常!", withDescription: "", in: self)
                      // self.tableView.mj_header?.endRefreshing()
                   }
               }

    }


}

